<?php
/**
 * Created by PhpStorm.
 * User: qch
 * Date: 2015/7/6
 * Time: 10:10
 */

namespace Aoe\Util;


use DateTime;

/**
 * # 日期工具
 *  * 时日 用时间戳
 *  * 年月及日期直接化为整数 2020-02-02 => 20202020
 *
 */
class DateTool
{
    const string F_TIME  = 'Y-m-d H:i:s';
    const string F_MONTH = 'Y-m';
    const string F_DAY   = 'Y-m-d';
    
    public static function int2str(int $value, $format = null): string
    {
        if (empty($value)) return '';

        // 默认为时间格式
        if ($format === null || $format === static::F_TIME)
            return date_create()->setTimestamp($value)->format($format);

        $str = $value . '';

        if ($format === static::F_DAY)
            return substr($str, 0, strlen($str) -4)
                . '-'
                .substr($str, -4, 2)
                . '-'
                . substr($str, -2);

        if ($format === static::F_MONTH)
            return substr($str, 0, strlen($str) -2)
                . '-'
                .substr($str, -2);

        return '';
    }
    
    public static function str2int(string $value, $format = null): ?int
    {
        if (empty($format) || $format === static::F_TIME) {
            $date = DateTime::createFromFormat(static::F_TIME, $value);
            return $date ? $date->getTimestamp() : null;
        }

        return (int)strtr($value, ['-' => '']);
    }
}